<?php
namespace app\admin\controller\yunfood\marketing;

use app\admin\model\yunfood\Promotion as PromotionModel;
use addons\yunfood\library\Backend;

class Promotion extends Backend
{
    protected $model = null;
    protected $noNeedRight = ['selectpage'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new PromotionModel();
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("typeList", $this->model->getTypeList());
        $this->view->assign("exclusiveList", $this->model->getExclusiveList());
        $this->view->assign("autoReceiveList", $this->model->getAutoReceiveList());
    }

    public function index()
    {
        if ($this->request->isAjax()) {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($where)
                ->order($sort, $order)
                ->count();
            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }

        return $this->view->fetch();
    }

    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $condition = $this->request->post("condition/a");
            $result = $this->request->post("result/a");
            
            if ($params) {
                // 处理店铺ID数组
                if (isset($params['shop_ids']) && is_array($params['shop_ids'])) {
                    $params['shop_ids'] = json_encode($params['shop_ids']);
                }
                
                // 如果是优惠券类型，处理优惠券特有字段
                if (isset($params['type']) && $params['type'] == 2) {
                    // 设置默认值
                    if (!isset($params['amount'])) $params['amount'] = 0;
                    if (!isset($params['limit'])) $params['limit'] = 0;
                    if (!isset($params['count'])) $params['count'] = -1;
                    if (!isset($params['receive_limit'])) $params['receive_limit'] = -1;
                    if (!isset($params['auto_receive'])) $params['auto_receive'] = 2;
                }
                
                try {
                    // 开启事务
                    \think\Db::startTrans();
                    
                    // 保存促销主信息
                    $promotionResult = $this->model->save($params);
                    if ($promotionResult === false) {
                        throw new \Exception($this->model->getError());
                    }
                    
                    // 获取插入的促销ID
                    $promotionId = $this->model->id;
                    
                    // 保存促销条件
                    if ($condition) {
                        $conditionData = [
                            'code' => ['ORDER_FULL'],
                            'sort' => [100],
                            'params' => [
                                ['amount' => $condition['params']['amount']]
                            ]
                        ];
                        $this->model->saveConditions($promotionId, $conditionData);
                    }
                    
                    // 保存促销结果
                    if ($result) {
                        $resultData = [
                            'code' => ['ORDER_REDUCE'],
                            'sort' => [100],
                            'params' => [
                                ['amount' => $result['params']['amount']]
                            ]
                        ];
                        $this->model->saveResults($promotionId, $resultData);
                    }
                    
                    // 提交事务
                    \think\Db::commit();
                    $this->success();
                } catch (\think\exception\PDOException $e) {
                    \think\Db::rollback();
                    $this->error($e->getMessage());
                } catch (\Exception $e) {
                    \think\Db::rollback();
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        
        // 获取店铺列表供选择
        $shopList = \app\admin\model\yunfood\Shop::column('name', 'id');
        $this->view->assign("shopList", $shopList);
        return $this->view->fetch();
    }

    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $condition = $this->request->post("condition/a");
            $result = $this->request->post("result/a");
            
            if ($params) {
                // 处理店铺ID数组
                if (isset($params['shop_ids']) && is_array($params['shop_ids'])) {
                    $params['shop_ids'] = json_encode($params['shop_ids']);
                }
                
                // 如果是优惠券类型，处理优惠券特有字段
                if (isset($params['type']) && $params['type'] == 2) {
                    // 设置默认值
                    if (!isset($params['amount'])) $params['amount'] = 0;
                    if (!isset($params['limit'])) $params['limit'] = 0;
                    if (!isset($params['count'])) $params['count'] = -1;
                    if (!isset($params['receive_limit'])) $params['receive_limit'] = -1;
                    if (!isset($params['auto_receive'])) $params['auto_receive'] = 2;
                }
                
                try {
                    // 开启事务
                    \think\Db::startTrans();
                    
                    // 保存促销主信息
                    $promotionResult = $row->save($params);
                    if ($promotionResult === false) {
                        throw new \Exception($row->getError());
                    }
                    
                    // 删除原有的促销条件和结果
                    \think\Db::name('jshop_promotion_condition')->where('promotion_id', $ids)->delete();
                    \think\Db::name('jshop_promotion_result')->where('promotion_id', $ids)->delete();
                    
                    // 保存促销条件
                    if ($condition) {
                        $conditionData = [
                            'code' => ['ORDER_FULL'],
                            'sort' => [100],
                            'params' => [
                                ['amount' => $condition['params']['amount']]
                            ]
                        ];
                        $this->model->saveConditions($ids, $conditionData);
                    }
                    
                    // 保存促销结果
                    if ($result) {
                        $resultData = [
                            'code' => ['ORDER_REDUCE'],
                            'sort' => [100],
                            'params' => [
                                ['amount' => $result['params']['amount']]
                            ]
                        ];
                        $this->model->saveResults($ids, $resultData);
                    }
                    
                    // 提交事务
                    \think\Db::commit();
                    $this->success();
                } catch (\think\exception\PDOException $e) {
                    \think\Db::rollback();
                    $this->error($e->getMessage());
                } catch (\Exception $e) {
                    \think\Db::rollback();
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        
        // 获取店铺列表供选择
        $shopList = \app\admin\model\yunfood\Shop::column('name', 'id');
        $this->view->assign("shopList", $shopList);
        
        // 处理店铺ID JSON数据
        if ($row->shop_ids) {
            $row->shop_ids = json_decode($row->shop_ids, true);
        }
        
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    public function del($ids = "")
    {
        if ($ids) {
            $this->model->destroy($ids);
            $this->success();
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }
}